import React from 'react';
import moment from 'moment';
import { Spin } from 'antd';
import ScheduleTable from './ScheduleTable';
import { getScheduleInfos } from '../../../service';

const Schedule = React.forwardRef(
    (
        {
            employeeCodes = [],
            date,
            timeRange = [],
            onRangeChange,
            rangeTitle,
            height,
            onChange,
            excludeInterviewCodes = [],
            isShowConflictControl = true
        },
        ref
    ) => {
        const [userList, setUserList] = React.useState([]);
        const [loading, setLoading] = React.useState(false);
        const tableRef = React.useRef();
        const isMounted = React.useRef();

        const queryDate = (date ?? moment()).format('YYYY-MM-DD');
        const startTimeStr = moment(timeRange[0] || undefined).format('HH:mm');
        const endTimeStr = moment(timeRange[1] || undefined).format('HH:mm');

        // 有效的时间
        const isValidTime = timeRange[0] && timeRange[1] && timeRange[0] < timeRange[1];

        const fetchUserList = async () => {
            setLoading(true);
            const result = await getScheduleInfos({ queryDate, employeeCodes });
            if (!isMounted.current) return;
            setLoading(false);
            if (result.code === 10000) {
                setUserList(
                    result.data.map(item => ({
                        id: item.employeeCode,
                        name: item.employeeName,
                        rangeList: item.scheduleInfos.map(it => ({
                            id: it.id,
                            title: it.scheduleTitle,
                            detailRange: [it.scheduleStartTime, it.scheduleEndTime],
                            businessRefCode: it.businessRefCode // 业务属性
                        }))
                    }))
                );
            }
        };

        React.useEffect(() => {
            if (userList.length && excludeInterviewCodes.length) {
                console.log(userList, 'xxx999');
                console.log(
                    userList.filter(item => ({
                        ...item,
                        rangeList: item.rangeList.filter(it => !excludeInterviewCodes.includes(it.businessRefCode)) // 如果是编辑，过滤掉当前编辑的日程安排
                    })),
                    'xxx999'
                );
                setUserList(
                    userList.map(item => ({
                        ...item,
                        rangeList: item.rangeList.filter(it => !excludeInterviewCodes.includes(it.businessRefCode)) // 如果是编辑，过滤掉当前编辑的日程安排
                    }))
                );
            }
        }, [JSON.stringify(userList), JSON.stringify(excludeInterviewCodes)]);

        React.useEffect(() => {
            isMounted.current = true;
            fetchUserList();
            return () => {
                isMounted.current = false;
            };
        }, [queryDate, JSON.stringify(employeeCodes)]);

        React.useEffect(() => {
            if (onChange) {
                onChange(!tableRef.current?.checkConflict());
            }
        }, [queryDate, startTimeStr, endTimeStr, userList]);

        const range = [`${queryDate} ${startTimeStr}`, `${queryDate} ${endTimeStr}`];

        const props = {
            userList,
            range,
            onRangeChange,
            rangeTitle,
            height,
            isValidTime,
            autoScroll: true,
            isShowConflictControl,
            date
        };

        return (
            <Spin spinning={loading}>
                <ScheduleTable ref={ref} tableRef={tableRef} {...props} />
            </Spin>
        );
    }
);

export default Schedule;
